package edu.itla.medifacil.persistence.managers;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.DoctorSpeciality;
import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.entities.Speciality;
import edu.itla.medifacil.persistence.enums.Role;

public class DoctorManager {
	private EntityManager em = null;
	
	public DoctorManager(){
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	
	public People save( Map<String, String> parameters){
		PersonManager doctorManager = new PersonManager();
		SpecialityManager specialityManager = new SpecialityManager();
		People doctor = doctorManager.save(parameters, Role.DOCTOR.getId());
		
		em.getTransaction().begin();
		
		em.createQuery( "DELETE FROM DoctorSpeciality WHERE doctor_id =" + doctor.getId() ).executeUpdate();
		
		for( String key : parameters.keySet() ){
			if( key.startsWith("specialities") ){
				int specialityId = Integer.parseInt( parameters.get(key) );
				DoctorSpeciality doctorSpeciality = new DoctorSpeciality();
				Speciality speciality = specialityManager.find( specialityId );
				doctorSpeciality.setSpeciality(speciality);
				doctorSpeciality.setPeople(doctor);
				em.persist( doctorSpeciality );
			}
		}
		
		em.getTransaction().commit();
		
		return doctor;
		
	}
	
	public void delete( int doctorId ){
		PersonManager doctorManager = new PersonManager();
		doctorManager.delete(doctorId);
	}
	
	public People find( int doctorId ){
		em.clear();
		return em.find( People.class, doctorId );
	}
	
	@SuppressWarnings("unchecked")
	public List<People> findAll(){
		return (List<People>) em.createQuery( "SELECT p FROM People p WHERE p.user.role.id =" + edu.itla.medifacil.persistence.enums.Role.DOCTOR.getId() ).getResultList();
	}

}
